package com.api.oa.services.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.api.oa.common.ToolUtils;
import com.api.oa.common.UserType;
import com.api.oa.config.EmServer;
import com.api.oa.config.UserContext;
import com.api.oa.exception.BadRequestException;
import com.api.oa.mapper.YQInsEntityMapper;
import com.api.oa.mapper.YQMedCareMapper;
import com.api.oa.mapper.YQUserMapper;
import com.api.oa.model.entity.YQInsEntity;
import com.api.oa.model.entity.YQMedCare;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.vo.YQInsEntityVO;
import com.api.oa.model.vo.YQMedCareVO;
import com.api.oa.services.YQMedCareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class YQMedCareServiceImpl implements YQMedCareService {

    @Autowired
    private YQMedCareMapper mapper;
    @Autowired
    private YQUserMapper yqUserMapper;
    @Autowired
    private YQInsEntityMapper yqInsEntityMapper;

    @Override
    public Integer add(YQMedCare entity) throws Exception {

        if (UserContext.getRole() == UserType.INS) {
            entity.setMedIns(UserContext.getInsCode());
        }
        if (StrUtil.isEmpty(entity.getMedIns())) {
            throw new BadRequestException("机构编码不能为空");
        }
        //判断机构是否已经存在 合法性，不存在 抛出异常
        Integer exit = yqInsEntityMapper.isExit(entity.getMedIns());
        if (exit == 0) {
            throw new BadRequestException("机构编码不合法");
        }

        if (StrUtil.isEmptyIfStr(entity.getMedRole()) || entity.getMedRole() > 2) {
            throw new BadRequestException("医护角色不合法");
        }
        //身份证号...
        if (StrUtil.isEmpty(entity.getMedIdCard()) || !IdcardUtil.isValidCard(entity.getMedIdCard())) {
            throw new BadRequestException("身份证号不合法");
        }
        YQUser oneByIDCard = yqUserMapper.findOneByIDCard(entity.getMedIdCard());
        if (oneByIDCard == null) {
            YQUser yqUser = new YQUser();
            yqUser.setUserType(entity.getMedRole()); //医护
            yqUser.setCreatedAt(new Date());
            yqUser.setStatus(0);
            yqUser.setIdCard(entity.getMedIdCard());
            yqUser.setPhone(entity.getMedPhone());
            yqUser.setUname(entity.getMedName());
            yqUser.setBelongInsCode(entity.getMedIns()); //所属机构编码
            yqUser.setPasswd(SecureUtil.md5("123456"));
            yqUserMapper.insert(yqUser);
            String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
            yqUser.setEmUuid(imUser);
        } else {
            oneByIDCard.setBelongInsCode(entity.getMedIns()); //所属机构编码
            oneByIDCard.setIdCard(entity.getMedIdCard());
            oneByIDCard.setPhone(entity.getMedPhone());
            oneByIDCard.setUserType(entity.getMedRole());
            oneByIDCard.setUname(entity.getMedName());
            yqUserMapper.update(oneByIDCard);
        }
        YQMedCare yqMedCare = mapper.findOneByIDCard(entity.getMedIdCard());
        if (yqMedCare != null) {
            throw new Exception("身份证信息已经存在");
        }

        return mapper.insert(entity);
    }

    @Override
    public void remove(String id) {
        mapper.delete(id);
    }

    @Override
    public Integer update(YQMedCare entity) {
        return mapper.update(entity);
    }

    @Override
    public PageInfo<YQMedCare> list(Long pid, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,medIdCard desc");
        return new PageInfo<>(mapper.list(pid));
    }

    @Override
    public PageInfo<YQMedCareVO> page(String idCard, String insCode, String role, Integer pageIndex, Integer pageSize) {
        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode(); //只有机构 才会有值
        }
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,medIdCard desc");
        return new PageInfo<>(mapper.page(idCard, insCode, role));
    }

    @Override
    public YQMedCare one(Long id) {
        return mapper.findOne(id);
    }

    @Autowired
    EmServer emServer;

    @Override
    @Transactional
    public void addBatch(List<YQMedCare> entities) throws BadRequestException {
        for (int i = 0; i < entities.size(); i++) {
            YQMedCare yqMedCare = entities.get(i);

            if (StrUtil.isEmpty(yqMedCare.getMedIns())) {
                throw new BadRequestException("机构编码不能为空");
            }


            if (StrUtil.isEmptyIfStr(yqMedCare.getMedRole()) || yqMedCare.getMedRole() > 2) {
                throw new BadRequestException("医护角色不合法");
            }
//            if (StrUtil.isEmpty(yqMedCare.getMedPhone())) {
//                throw new BadRequestException("手机号不能空");
//            }

//            if (!PhoneUtil.isPhone(yqMedCare.getMedPhone())) {
//                throw new BadRequestException("手机号不合法");
//            }

            //身份证号...
            if (StrUtil.isEmpty(yqMedCare.getMedIdCard()) || !IdcardUtil.isValidCard(yqMedCare.getMedIdCard())) {
                throw new BadRequestException("身份证号不合法");
            }

        }

        if (entities.size() != entities.stream().map(YQMedCare::getMedIdCard).distinct().count()) {
            throw new BadRequestException("身份证有重复");
        }

        for (int i = 0; i < entities.size(); i++) {
            YQMedCare yqMedCare = entities.get(i);

            //判断机构是否已经存在 合法性，不存在 抛出异常
            Integer exit = yqInsEntityMapper.isExit(yqMedCare.getMedIns());
            if (exit == 0) {
                continue;
            }

            YQMedCare oneByPhone = mapper.findOneByIDCard(yqMedCare.getMedIdCard());
            if (oneByPhone == null) {
                mapper.insert(yqMedCare);
            } else {
                mapper.update(yqMedCare);
            }
            YQUser oneByIDCard = yqUserMapper.findOneByIDCard(yqMedCare.getMedIdCard());
            if (oneByIDCard == null) {
                YQUser yqUser = new YQUser();
                yqUser.setUserType(yqMedCare.getMedRole()); //医护
                yqUser.setCreatedAt(new Date());
                yqUser.setStatus(0);
                yqUser.setUname(yqMedCare.getMedName());
                yqUser.setBelongInsCode(yqMedCare.getMedIns()); //所属机构编码
                yqUser.setIdCard(yqMedCare.getMedIdCard());
                yqUser.setPhone(yqMedCare.getMedPhone());
                yqUser.setPasswd(SecureUtil.md5("123456"));
                yqUserMapper.insert(yqUser);
                String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
                yqUser.setEmUuid(imUser);
            } else {
                oneByIDCard.setBelongInsCode(yqMedCare.getMedIns()); //所属机构编码
                oneByIDCard.setIdCard(yqMedCare.getMedIdCard());
                oneByIDCard.setPhone(yqMedCare.getMedPhone());
                oneByIDCard.setUname(yqMedCare.getMedName());
                oneByIDCard.setUserType(yqMedCare.getMedRole());
                yqUserMapper.update(oneByIDCard);
            }
        }
    }

    @Override
    public List<YQMedCareVO> queryMedByInsCode(String insCodeUser) {
        if (UserContext.getRole() == UserType.INS) {
            insCodeUser = UserContext.getInsCode();
        }
        return mapper.queryMedByInsCode(insCodeUser);
    }

    @Override
    public void export(String idCard, String insCode, String role, Integer pageIndex, Integer pageSize, HttpServletResponse res) throws IOException {
        List<YQMedCareVO> page = mapper.page(idCard, insCode, role);
        List<Map<String, Object>> collect = page.stream().map(i -> {
            Map<String, Object> map = new HashMap<>();
            map.put("姓名", i.getMedName());
            map.put("性别", i.getMedSex());
            map.put("照片", i.getMedFace());
            map.put("身份证", i.getMedIdCard());
            map.put("手机号", i.getMedPhone());
            map.put("身份", i.getMedRole());
            map.put("机构", i.getMedIns());
            map.put("证书URL", i.getMedCert());
            map.put("证书编码", i.getMedCertCode());
            map.put("禁用", i.getDisabled());
            map.put("创建时间", i.getCreatedAt());
            map.put("机构名称", i.getInsName());
            return map;
        }).collect(Collectors.toList());
        ToolUtils.downLoadExcel(collect, res);
    }




}
